import { codo, Controller } from "egg";
import { hc } from "../hc";

/**
 * 示例的控制器接收设备数据如何处理
 */
export default class BaseHaiQingWANMainController extends Controller {
	// @post("/open/hc/wan/heartbeat")
	async heartbeat() {
		const body = this.ctx.request.body as hc.wan.heartbeatBody;
		if (!body.data || !body.info || !body.operator) {
			return;
		}
		this.logger.debug("广域网接收hc心跳交互 %j", body);
		const obj: codo.hc.http.device = {
			id: "1",
			deviceId: body.info.DeviceID,
			name: "",
			ip: this.ctx.request.ip,
			user: "a:1",
		};
		const device = this.app.codo.hc.device.getWanServiceInstance(obj);

		// 如果心跳中携带上次命令的执行结果，则存入redis等待处理
		if (!body.data?.OperatorInfo?.operator) return;
		if (body.data?.OperatorInfo?.operator !== "none") {
			device.tools.cmdResultSetRedis(body.data.TaskId.toString(), body.data);
		}

		// 如果设备空闲，则查询是否有新任务并下发
		if (body.data.StateCode === 0) {
			const row = await device.tools.getCacheCMD();
			if (!row) return this.resOnFree(body.info.DeviceID);
			const cmdObj = device.tools.createCMDObject(row);
			// this.logger.debug(`hc wan 下发命令body: \r\n %j`, cmdObj);
			this.ctx.body = cmdObj;
			this.ctx.status = 200;
		} else {
			// 设备不空闲，直接回复无需下发新命令
			this.resOnFree(body.info.DeviceID);
		}
	}

	/** 回复设备当前没有命令需要下发 */
	private resOnFree(deviceId: string | number) {
		const body: hc.wan.cmdResponse<{}> = {
			TimeStamp: new Date().getTime(),
			TaskId: 0,
			OperatorInfo: {
				operator: "none",
				DeviceID: deviceId,
			},
		};
		this.ctx.status = 200;
		this.ctx.body = body;
	}
}
